const app = getApp()
const http = require('../../../utils/util')
const {baseurl} = require('../../../utils/util')
const Base64 = require('../../../utils/base')
const localData = require("../../../utils/localData")
const time_data = require('../../../utils/data')

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		hold_time:[], //占用时间段
		seat_num:'', //正在占用的座位号
		showHite:'none', //灰色座位弹出层
		conduct:'', //自习室守则内容
		seatRule:'none', //自习室守则
		seatClass: 'none', //座位平面图显示隐藏
		seat_params: {}, //上个页面传递过来的参数
		seatList: [], //座位列表数据
		arr: [], //选中座位的id
		genre_id: '', //座位类型id

		currentPrice: '', //选中的座位价格
		shop_name: '',
		shop_address: '',
		all_date: {},

		timeList: [], //json时间段数据
		newTimeList: [],
		pickerDate: '',
		start_hours: '',
		end_hours: '',
		location_img: '',
		max_num: 2,
		name:'',
		list:[],
		
		second:0, //倒计时跳转
		interval:false, //
		
		windowHeight:'',
		windowWidth:''
	},

	//获取座位信息
	getSeatData() {
		let data = {
			user_id: wx.getStorageSync('user_id'),
			user_token: wx.getStorageSync('user_token'),
			store_id: this.data.seat_params.store_id,
			start_time: this.data.pickerDate + ' ' + this.data.start_hours,
			end_time: this.data.pickerDate + ' ' + this.data.end_hours
		}
		http.post('store/genre', Base64.encode(JSON.stringify(data))).then((res) => {
			if (res.status == 1) {
				this.setData({
					seatList: res.result
				})
			} else {
				wx.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	},
	//选择日期
	bindDateChange(e) {
		// 清除选定的座位信息
		this.setData({
			arr:[],
			name:'',
			genre_id:''
		})
		let shop_start_MS = new Date(this.data.seat_params.start_date).getTime()
		let current_MS = new Date(e.detail.value).getTime()
		if (current_MS > shop_start_MS) {
			let shop_start_time=this.data.seat_params.shop_start_time
			let date = e.detail.value + ' ' + shop_start_time
			let hours=shop_start_time.split(':')[0].toString().length==1?'0'+shop_start_time.split(':')[0]:shop_start_time.split(':')[0]
			let minute=shop_start_time.split(':')[1].toString().length==1?'0'+shop_start_time.split(':')[1]:shop_start_time.split(':')[1]
			let start_hours=hours+':'+minute
			this.setData({
				pickerDate: e.detail.value,
				start_hours: start_hours,
				end_hours: time_data.new_hours(date).end_time,
			}, () => {
				this.getSeatData()
				this.filterPrickHours(start_hours)
			})
		} else {
			let timelist = this.data.timeList
			let shop_start = this.data.seat_params.shop_start_time
			let start = time_data.new_hours().start_time
			let end = this.data.seat_params.end_hours
			let startIndex = null
			let endIndex = null
			let shopStartIndex = null
			timelist.forEach((item, index) => {
				if (item == start) {
					startIndex = index
				}
				if (item == end) {
					endIndex = index
				}
				if (item == shop_start) {
					shopStartIndex = index
				}
			})
			if (startIndex >= endIndex) {
				return this.setData({
					pickerDate: e.detail.value,
					newTimeList: [],
					start_hours: this.data.seat_params.shop_end_time,
					end_hours: this.data.seat_params.shop_end_time
				}, () => {
					this.getSeatData()
					this.filterPrickHours(this.data.seat_params.shop_end_time)
				})
			}
			if (startIndex < shopStartIndex) {
				let date=this.data.seat_params.start_date+' '+shop_start
				return this.setData({
					pickerDate: e.detail.value,
					newTimeList: timelist.slice(shopStartIndex, endIndex + 1),
					start_hours: shop_start,
					end_hours: time_data.new_hours(date).end_time,
					["list[0]"]:timelist.slice(shopStartIndex, endIndex + 1),
					["list[1]"]:timelist.slice(shopStartIndex+1, endIndex + 1),
				}, () => {
					this.getSeatData()
					this.filterPrickHours(shop_start)
				})
			}

			this.setData({
				pickerDate: e.detail.value,
				newTimeList: timelist.slice(startIndex, endIndex + 1),
				start_hours: time_data.new_hours().start_time,
				end_hours: time_data.new_hours().end_time,
				["list[0]"]:timelist.slice(startIndex, endIndex + 1),
				["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
			}, () => {
				this.getSeatData()
				this.filterPrickHours(this.data.seat_params.start_hours)
			})

		}

	},

	// 选中座位
	changeSeat(e) {
		console.log(e);
		let current = e.currentTarget.dataset.item //当前点击的座位信息
		if (current.check == 1){ //点击灰色座位
			//发请求获取当前座位信息
			this.setData({
				seat_num:current.seat_name
			})
			let data={
				sid:current.sid
			}
			http.post('store/seatTime', Base64.encode(JSON.stringify(data))).then(res=>{
				if(res.status==1){
					this.setData({
						hold_time:res.result
					})
				}else{
					wx.showToast({
						title:res.message,
						icon:'none'
					})
				}
			})
			return this.setData({
				showHite:'show'
			})
		} //check属性为1时不可点击
		if(this.data.arr==current.id){
			this.setData({
				arr:[],
				name:'',
				genre_id: ''
			})
		}else{
			this.setData({
				["arr[0]"]:current.id,
				name:current.seat_name,
				genre_id: current.genre_id
			})
		}
	},
	//选定座位对应的价格
	changePrice(e) {
		let index = e.currentTarget.dataset.index
		this.setData({
			currentPrice: this.data.seatList[index].price,
			shop_name: this.data.seatList[index].store_name,
			shop_address: this.data.seatList[index].address
		})
	},
	//显示座位平面图
	openPlan() {
		this.setData({
			seatClass: 'show'
		})
	},
	hidePlan() {
		this.setData({
			seatClass: 'hide'
		})
		setTimeout(() => {
			this.setData({
				seatClass: 'none'
			})
		}, 200)
	},
	
	//隐藏自习室守则
	hideSeatRule(){
		this.setData({
			interval:true,
			seatRule:'none'
		})
		this.setData({
			seatRule: 'hide'
		})
		setTimeout(() => {
			this.setData({
				seatRule: 'none'
			})
		}, 200)
	},
	
	//隐藏灰色座位弹出层
	hitehide(){
		this.setData({
			showHite: 'hide'
		})
		setTimeout(() => {
			this.setData({
				showHite: 'none'
			})
		}, 200)
	},
	//预约按钮点击事件 
	onMakeBtnEvent() {
		let _this = this
		
		//判断用户是否登录
		let user_token = wx.getStorageSync('user_token')
		if (!user_token) {
			wx.showModal({
				title: '提示',
				content: '你还没有登陆，是否登录?',
				success(res) {
					if (res.confirm) {
						wx.clearStorageSync()
						_this.login()
					}
				}
			})
			return
		}

		//判断用户是否选择座位
		if (this.data.arr.length == 0) {
			return wx.showToast({
				title: '请选择座位',
				icon: 'none'
			})
		}
		
		
		//判断用户选择时间是否合理
		let currentSeat= this.data.seatList.filter(v=>v.genre_id==this.data.genre_id)
		let start_minute=currentSeat[0].minute
		//判断用户选择时间段
		let s=this.data.pickerDate + ' ' + this.data.start_hours+':00'
		let e=this.data.pickerDate + ' ' + this.data.end_hours+':00'
		let start_MS = new Date(s.replace(/-/g,'/')).getTime()
		let end_MS = new Date(e.replace(/-/g,'/')).getTime()
		if(end_MS<=start_MS){
			return wx.showToast({
				title: `结束时间不能小于开始时间`,
				icon: 'none'
			})
		}
		if ((end_MS - start_MS) < start_minute*60*1000) {
			return wx.showToast({
				title: `预约时间不能低于${start_minute}分钟`,
				icon: 'none'
			})
		}
		
		//订阅消息授权
		// wx.requestSubscribeMessage({
		// 	tmplIds:['ig9l3u4D9mShf6ZxHwl7tBnrskYbh84jyCNF8SzvHfc'],
		// 	complete:()=>{
		// 		this.roomRules()
		// 	}
		// })
		this.roomRules()
	},
	//判断是否弹出自定义守则，进入提交订单页面
	roomRules(){
		//判断是否弹出自定义守则
		let params={
			user_id:wx.getStorageSync('user_id'),
			user_token:wx.getStorageSync('user_token'),
			store_id:this.data.seat_params.store_id
		}
		http.post('store/stipulate', Base64.encode(JSON.stringify(params))).then(res=>{
			if(res.status==1){
				if(res.result.status==0){
					
					if(!res.result.conduct){  //自习室守则内容为空时,不弹出提示框直接进入提交订单页
						this.setData({
							second:0
						})
						//去往提交订单页
						this.navigateSubOrder()
						return
					}
					
					this.setData({
						seatRule:'show',
						conduct:res.result.conduct.replace('<img ', '<img style="max-width:100%;height:auto;"')
					},()=>{
						let interval= setInterval(()=>{
							if(this.data.interval || this.data.second<=0){
								clearInterval(interval)
							}
							this.setData({
								second: --this.data.second
							})
						},1000)
					})
				}else{
					this.setData({
						second:0
					})
					//去往提交订单页
					this.navigateSubOrder()
				}
			}else{
				wx.showToast({
					title: res.message,
					icon: 'none'
				})
			}
		})
	},
	//乘法计算精度
	accMul(arg1,arg2) 
	 { 
	 var m=0,s1=arg1.toString(),s2=arg2.toString(); 
	 try{m+=s1.split(".")[1].length}catch(e){} 
	 try{m+=s2.split(".")[1].length}catch(e){} 
	 return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) 
	 },
	//跳转提交订单页
	navigateSubOrder(){
		//倒计时10s内点击无效不做跳转
		if(this.data.second>0) return
		this.setData({
			interval:true,
			seatRule:'none'
		})
		//带参数去往入座订单页面
		let end = this.data.seat_params.end_hours.replace(':', '.')
		let start = this.data.seat_params.start_hours.replace(':', '.')
		
		
		//共计多少小时
		let s=this.data.pickerDate + ' ' + this.data.start_hours+':00'
		let e=this.data.pickerDate + ' ' + this.data.end_hours+':00'
		let start_MS = new Date(s.replace(/-/g,'/')).getTime()
		let end_MS = new Date(e.replace(/-/g,'/')).getTime()
		let hours = (end_MS - start_MS) / 3600000
		//预计费用
		let subtotal = this.accMul(this.data.currentPrice,hours)
		// 星期几
		let week=new Date(this.data.pickerDate.replace(/-/g,'/')).getDay()
		switch (week){
			case 0:
				week='周日'
				break
			case 1:
				week='周一'
				break
			case 2:
				week='周二'
				break
			case 3:
				week='周三'
				break
			case 4:
				week='周四'
				break
			case 5:
				week='周五'
				break
			case 6:
				week='周六'
				break
		}
		let data = {
			seat_num: this.data.arr, //座位id
			seat_name: this.data.name, //座位名称
			predict_price: this.data.currentPrice, //预估费用
			shop_name: this.data.shop_name,
			shop_address: this.data.shop_address,
			store_id: this.data.seat_params.store_id, // 门店id
			genre_id: this.data.genre_id, //座位类型id
			date: this.data.pickerDate, //预约日期
			start_hours: this.data.start_hours, //预约开始时间
			end_hours: this.data.end_hours, //预约结束时间
			hours: hours,
			subtotal: subtotal, //小计
			store_money:this.data.seat_params.store_money,
			weekday:week
		}
		wx.navigateTo({
			url: '/pages/store/seatorder/seatorder?data=' + JSON.stringify(data)
		})
	},
	//座位相册
	goAtlas(e) {
		let params={
			genre_id:e.currentTarget.dataset.genreid,
			store_id:this.data.seat_params.store_id
		}
		wx.navigateTo({
			url: '/pages/mine/atlas/atlas?params=' + JSON.stringify(params)
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let seat_params = JSON.parse(options.seat_params)
		app.globalData.seat_params=seat_params
		this.setData({
			timeList: localData.timeList,
			seat_params: seat_params,
			all_date: app.globalData,
			pickerDate: seat_params.currentDate,
			start_hours: seat_params.start_hours,
			end_hours: seat_params.end_hours,
			location_img: baseurl + seat_params.location_img
		})
		//获取座位信息
		this.getSeatData()
	},

	//登录
	login() {
		wx.login({
			success(res) {
				if (res.code) {
					wx.setStorageSync('code', res.code)
				} else {}
			}
		})
		const _this = this
		wx.getUserProfile({
			desc: '获取用户相关信息',
			success: function(obj) {
				let code = wx.getStorageSync('code')
				var data = {
					code: code,
					encryptedData: obj.encryptedData,
					iv: obj.iv,
				}
				http.post('wechat/login', Base64.encode(JSON.stringify(data))).then(res => {
					if (res.status != 1) {}
					wx.setStorageSync('user_id', res.result.user_id)
					wx.setStorageSync('user_token', res.result.user_token)
					wx.setStorageSync('phone', res.result.phone)
					wx.showToast({
						title: '登录成功',
						icon: 'none'
					})

				})
			},
			fail: function(obj) {}
		})
	},
	//筛选时间选择器时间段
	filterPrickHours(start_hours) {
		let timelist = this.data.timeList
		let start = start_hours
		let end = this.data.seat_params.shop_end_time
		let startIndex = null
		let endIndex = null
		this.data.timeList.forEach((item, index) => {
			if (item == start) {
				startIndex = index
			}
			if (item == end) {
				endIndex = index
			}
		})
		this.setData({
			newTimeList: timelist.slice(startIndex, endIndex + 1),
			["list[0]"]:timelist.slice(startIndex, endIndex + 1),
			["list[1]"]:timelist.slice(startIndex+1, endIndex + 1),
		})
	},

	//多列选择器
	multiSelector(e){
		// 清除选定的座位信息
		this.setData({
			arr:[],
			name:'',
			genre_id:''
		})
		let start_index=e.detail.value[0]
		let end_index=e.detail.value[1]
		let start_hours=this.data.list[0][start_index]
		let end_hours=this.data.list[1][end_index]
		this.setData({
			start_hours:start_hours,
			end_hours:end_hours,
		},()=>{
			this.getSeatData()
		})
	},
	//列改变时触发
	columnchange(e){
		let list=this.data.list[0]
		let index=e.detail.value
		if(e.detail.column==0){ //左边选择列在动
			if(list.length==index+1){
				this.setData({
					['list[1]']:list.slice(index)
				})
			}else{
				this.setData({
					['list[1]']:list.slice(index+1)
				})
			}
		}
	},
	// px转换rpx
	rpxTopx(px) {
	 
	  let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
	 
	  let rpx = (750 / deviceWidth) * Number(px)
	 
	  return Math.floor(rpx);
	 
	},



	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {
		this.filterPrickHours(this.data.seat_params.start_hours)
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		
		let windowWidth=wx.getSystemInfoSync().windowWidth
		this.setData({
			windowWidth:windowWidth/10*9.2
		})
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
